class Solution
{
public:
    vector<int> dailyTemperatures(vector<int> &temperatures)
    {
        stack<int> nextGreater;
        int n = temperatures.size();
        vector<int> result(n);
        for (int i = n - 1; i >= 0; --i)
        {
            while (!nextGreater.empty())
            {
                if (temperatures[nextGreater.top()] <= temperatures[i])
                {
                    nextGreater.pop();
                }
                else
                {
                    break;
                }
            }
            if (nextGreater.empty())
            {
                result[i] = 0;
            }
            else
            {
                result[i] = nextGreater.top() - i;
            }
            nextGreater.push(i);
        }
        return result;
    }
};